// pages/works/works.js
let that,
correctLevel=3,
  api = new (require('../../utils/api.js')),
  util = new (require('../../utils/util.js')),
  qrcode = require('../../utils/qrcode.js'),
  headimg = api.getimgurl(),
  interval,
  imglist=[],
  
  imghead = 'https://techcherry.cn/hhlgsrc/',
  app = getApp();
  for (let index = 1; index < 35; index++) {
    imglist.push(index);
  }
Page({

  /**
   * 页面的初始数据
   */
  data: {
  
    shoplist:[
      {
        name:'上海星光照相器材批发市场经营管理有限公司',
        addr:'上海市黄埔区鲁班路300号'
      }
    ],
    ticket_mg:{
      giftname:"金字塔之巅95折券(有效期至5月31日)",

    },
    shopshowlist:[
    ],
    jingxitype:0,
    totalscore:0,
    totalcoupon:0,
    specailnum:1,
    firstscore:5,
    showyxsm:!1,
    showjfcj:!1,
    showjingxi:!1,
    openjingxi:!1,
    zhongjiang:0, 
    shoparr:['xxx1112233','上海市黄浦区淮海中路222号力宝广场1楼105-106单元','淮海中路845号','上海市黄浦区淮海中路766号 淮国旧2楼'],
    giftname:'XXXX身体乳',
    meizhong:1,
    showmyafterchou:!1,
    showticket:!1,
    showticketqrcode:!1,
    showmine:!1,
    mygiftshowqrcode:!1,
    showdakasucc:!1,
    showdaka:!1,
    showshopinfo:!1,
    showmygift:!1, 
    mygiftlist:[],
    showqbsj:!1,
    showshare:!1,
    shownew:!1,
    ticketmoney:'',
    ticketsrc:'',
    count:0,
    imglist,
    imghead,
    pagesize: 20,
    currentpage: 1,
    list: [],
    nocart:[],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    that=this;
    let logininfo = app.logininfo;
   // this.setData({ cartids });
   console.log(logininfo,'logininfo');
  //  that.setData({userid:app.logininfo.userid, 
  //   freegiftshowqrcode:!0,
  //   freegiftid:1,
  //  showticket:!0, 
  //  })

   that.setData({userid:app.logininfo.userid,  
    })
    that.getdata()
     wx.getSystemInfo({
            success: (res) => {
        
               new qrcode({
                width:  res.screenWidth * 0.16,
                height: res.screenWidth * 0.16,
                canvasId: 'canvas',
      correctLevel,
    
                text: 'https://techcherry.cn/hhlgqrcode?id='+logininfo.userid,
                callback: res => {
        console.log( res ,'new qrcode');
            wx.canvasToTempFilePath({
              canvasId:'canvas',
               width: res.screenWidth * 0.16,
                height: res.screenWidth * 0.16,
              success:res=>{
                console.log(res,'resres');  
                that.setData({ giftqrcode:res.tempFilePath,canvasimg:res.tempFilePath})
              },
              complete:res=>{
                console.log(res,'complete');
              }

            })

                }
              })
            },
      complete:res=>{
        console.log(res,'complete');
      }
          })


    // wx.showLoading({
    //   title: '加载中',
    // })

    if(options.t){
      this.setData({type:options.t},()=>{
       // that.getlist();
      });
    }
    
  },

  hidemygiftshowqrcode(){
    that.setData({mygiftshowqrcode:!1})
  },
  hidefreegiftshowqrcode(){
    that.setData({freegiftshowqrcode:!1})
  },

  resetticket(){
    that.setData({showticketqrcode:!1,hasupload:!1,ticketmoney:'',ticketqrcode:''})
  },

  getdata(){
    let logininfo = app.logininfo,{getsurprise}=logininfo;
    that.setData({getsurprise,totalscore:logininfo.score,buttonsharecount:logininfo.buttonshare})
    if(logininfo.isnew){
      that.setData({firstscore:logininfo.firstscore})
      api.addnew(res=>{
        if(res.data.issuccess==1){
  //获得积分弹窗
  that.setData({shownew:!0})
  setTimeout(() => {
      that.setData({shownew:!1})
    //  wx.setStorageSync('score', 5)
  }, 2000);
        }
      })
    }
    api.获取全部商户(res=>{
      if(res.data.issuccess==1){
        that.setData({shopshowlist:res.data.list})
      }
    })
    that.getdakalist()
  },
  mygift_select(e){
let{item} = e.currentTarget.dataset
  that.setData({mygiftshowqrcode:!0,mygift_checksrcid:item.freegiftid>0?item.freegiftid:item.giftsrc,mygift_checkname:item.giftname})
  api.根据奖品获取店铺({id:item.giftid,freegiftid:item.freegiftid},res=>{
    if(res.data.issuccess==1){
      that.setData({mygift_addresslist:res.data.list})
    }
  })
   wx.getSystemInfo({
          success: (res) => {
            new qrcode({
              width: res.screenWidth * 0.16,
              height: res.screenWidth * 0.16,
    correctLevel,
              canvasId: 'mygiftcanvas', 
              text: 'https://techcherry.cn/giftqrcode?id='+item.id,
              callback: res => {
          wx.canvasToTempFilePath({
            canvasId:'mygiftcanvas',
             width: res.screenWidth * 0.16,
              height: res.screenWidth * 0.16,
            success:res=>{
              that.setData({mygift_checkqrcode:res.tempFilePath})
            },
          })

              }
            })
          },
    complete:res=>{
      console.log(res,'complete');
    }
        })



  },

  getdakalist(){
    api.获取已打卡商户(res=>{
      if(res.data.issuccess==1){
        let shoplist= res.data.list,count = shoplist.length

        that.setData({count,shoplist})
      }
    })
  },

  cleantoast(){
    that.setData({
      choseitem:0,
      freegiftshowqrcode:!1,
      mygift_checkqrcode:'',
      showjingxi:!1,
      ticketmoney:'',
      hasupload:!1,
      openjingxi:!1,
      showticketqrcode:!1,
      showyxsm:!1,
      showmygift:!1,
      showshopinfo:!1,
      zhongjiang:0,
      meizhong:0,
      showticket:!1,
      showdaka:!1,
      showjfcj:!1,
      showmyafterchou:!1,
      showdakasucc:!1,
      mygiftshowqrcode:!1,
    showqbsj:!1,
    showmine:!1,
    showshare:!1,
    shownew:!1,
    })
  },
  展示随赠礼品(freegiftname,id,addrlist){
   // that.cleantoast()
   console.log('展示随赠礼品',{freegiftname,id,addrlist});   
   that.setData({showticketqrcode:!1,freegiftshowqrcode:!0})

    wx.getSystemInfo({
          success: (sysres) => {
      new qrcode({
                width:sysres.screenWidth * 0.16,
                height: sysres.screenWidth * 0.16,
                canvasId: 'freegiftcanvas',
      correctLevel,
                text: 'https://techcherry.cn/giftqrcode?id='+id,
                callback: res => {
        console.log('  new qrcode--callback',res);
            wx.canvasToTempFilePath({
              canvasId:'freegiftcanvas',
               width: sysres.screenWidth * 0.16,
                height:sysres.screenWidth * 0.16,
              success:res=>{
                console.log(res,'展示随赠礼品');   
                that.setData({freegift_checkqrcode:res.tempFilePath,freegiftid:id,freegiftname,freegift_addresslist:addrlist})
              },
              complete:res=>{
                console.log('canvasToTempFilePath---',res);
              }
            })
          },
    })
  }
})
  },
  ticket_check(){
    if(that.data.ticket_checking){
      return;
    }
    that.setData({ticket_checking:!0})
    let{ticketmoney,ticketsrc,hasupload} = that.data,err=''
    if(ticketmoney<=0) err='请输入正确的金额'
    if(ticketmoney>10000) err='输入金额不得超过10000'
    if(!hasupload||ticketsrc=='') err='请先上传小票'
    if(err!=''){
      util.nocancelmodal(err)
    }else{
      wx.showLoading({  
        title: '上传中',
      })
      api.上传小票(ticketsrc,ticketmoney,res1=>{
        wx.hideLoading()
        if(res1.data.issuccess==1){
          that.setData({showticketqrcode:!0,ticket_checking:!1})
           wx.getSystemInfo({
                  success: (res) => {
                    new qrcode({
                      width: 250,//res.screenWidth * 0.16,
                      height: 250, //res.screenWidth * 0.16,
                      canvasId: 'ticketqrcode',
            correctLevel,
                      text: 'https://techcherry.cn/tqrcode?id='+res1.data.id,
                      callback: res => {
                  wx.canvasToTempFilePath({
                    canvasId:'ticketqrcode',
                     width: 250,// res.screenWidth * 0.16,
                      height:250,// res.screenWidth * 0.16,
                    success:res=>{
                      console.log(res,'resres');  
                      that.setData({ticketqrcode:res.tempFilePath})
                      //设置轮询： 3秒一次 一共10次
                      var count = 0;
                       interval = setInterval(()=>{
                        count++;
                        api.查看随赠结果(res1.data.id,res2=>{
                          if(res2.data.mg!=null){
                            clearInterval(interval)
                            let {mg,addrlist} = res2.data
                            that.展示随赠礼品(mg.giftname,mg.freegiftid,addrlist)
                          }
                        })

                      },3000)
                     setTimeout(() => {
                       clearInterval(interval)
                     }, 60000);

                     



                    }
                  })
      
                      }
                    })
                  },
                })


        }

      })
    }
  },
  inputmoney(e){
    let {value}=e.detail
    that.setData({ticketmoney:value})
  },
  upload(){
    api.获取上传次数(res=>{
      if(res.data.time<5){
        wx.chooseMedia({
          count:1,
          sizeType:"compressed",
          success:res=>{
            let {size,tempFilePath} = res.tempFiles[0]
            if(size>1024*1024*2){
              util.nocancelmodal('图片不超过2M')
            }else{
              api.uploadimg({
                path: [tempFilePath] //这里是选取的图片的地址数组        
              }, {
                success: function (res) {
                  console.log(res,'success');
                  if(res[0]!=undefined){
                    that.setData({ticketsrc:res[0],hasupload:!0})
                  }else{

                  }
                },
                fail(res){
                  util.nocancelmodal(res)
                  that.setData({uploading:!1 });
                }
              });
            }
          }
        })
      }else{
        util.nocancelmodal('当日上传次数已满')
      }
    })
   
  },
  closezhong(){
    that.setData({zhongjiang:0,meizhong:0})
  },
  afterchou(e){
let {type} = e.currentTarget.dataset
wx.showLoading({
  title: '提交中',
})
api.抽奖(type,res=>{
  wx.hideLoading()
    if(res.data.issuccess==1){
      let{gift,shoplist,mygiftid,score} = res.data
      that.setData({totalscore:score})
      if(gift!=''){
        let shoparr = []
        shoplist.forEach(x=>{
          shoparr.push(x.addr)
        })
        that.setData({zhongjiang:1,giftsrc:gift.srcid,giftname:gift.name,shoparr})
         wx.getSystemInfo({
                success: (res) => {
                  new qrcode({
                    width: res.screenWidth * 0.16,
                    height: res.screenWidth * 0.16,
                    canvasId: 'giftcanvas',
          correctLevel,
                    text: 'https://techcherry.cn/giftqrcode?id='+mygiftid,
                    callback: res => {
                wx.canvasToTempFilePath({
                  canvasId:'giftcanvas',
                   width: res.screenWidth * 0.16,
                    height: res.screenWidth * 0.16,
                  success:res=>{
                    that.setData({giftqrcode:res.tempFilePath})
                  },
                })
    
                    }
                  })
                },
          complete:res=>{
            console.log(res,'complete');
          }
              })



      }else{
        let specailnum = Math.floor(Math.random() * 5) + 1
        that.setData({meizhong:1,specailnum})
      }
     
    }else{
      util.nocancelmodal(res.data.msg)
    }

})

  // let specailnum = Math.floor(Math.random() * 4) + 1;
  //  that.cleantoast()
  //  that.setData({specailnum,showmyafterchou:!0})
  },
  dakascan(){
    wx.scanCode({
      onlyFromCamera: true,
      success (res) {
        console.log('dakascan',res);
        if(res.result.indexOf('https://techcherry.cn/hhlg/shopscan?id=')>-1){
          let id= res.result.replace('https://techcherry.cn/hhlg/shopscan?id=','');
          console.log('有效扫码'+id);
          api.商户打卡(id,res=>{
            that.cleantoast()
            if(res.data.issuccess==1){
              that.getdakalist()
              that.setData({showdakasucc:!0,count:that.data.count+1})
            }else{
              wx.showToast({
                title: res.data.msg,
                icon:'none'
              })
            }
          })
          
          //加积分
          //加脚印

          // that.cleantoast()
          // that.setData({showdakasucc:!0,count:that.data.count+1})
        }else{
          that.cleantoast()
          wx.showToast({
            title: "无效的二维码",
            icon:'none'
          })
        }
      }
    })
  },
  seefreegift(){
    api.获取全部随赠店铺(res=>{
      if(res.data.issuccess==1){
        that.setData({showticket:!1,showqbsj:!0,showfreegift:!0, shopshowlist:res.data.list})
      }
    })

  },

  ticket(){
    that.cleantoast()
    that.setData({showticket:!0})
  },
  showpic(){
    console.log('showpic');
    wx.previewImage({
      urls: [that.data.canvasimg],
    })
  },

  previewmygiftqrcode(){
    console.log('showpic');
    wx.previewImage({
      urls: [that.data.mygift_checkqrcode],
    })
  },
  previewfreegiftqrcode(){
    wx.previewImage({
      urls: [that.data.freegift_checkqrcode],
    })
  },


  close(e){
  that.cleantoast()
  },
  opengift(){
    that.cleantoast()
    that.setData({showmygift:!0})
    api.获取全部礼物(res=>{
      if(res.data.issuccess==1){
          that.setData({mygiftlist:res.data.list})
      }
    })
  },
  showchoujiang(){
    that.cleantoast()
    that.setData({showjfcj:!0})
  },
  
  pushbtn(e){
    let {code} = e.currentTarget.dataset
    console.log(code,'code');
    if(code=='yxsm'||code=='share'||code=='qbsj'||code=='mine'){
      that.cleantoast()
      that.setData({['show'+code]:!0})
    }
    if(code==2){
      wx.showLoading({
        title: '加载中',
      })
      //打卡
      //概率抽奖 
      let {getsurprise} = that.data
      if(!getsurprise){
        //可参与抽奖
        api.惊喜礼盒(res=>{
          wx.hideLoading()
          if(res.data.issuccess==1){
            let jingxitype = 0;
            if(res.data.mg==null){
              jingxitype = 2
            }else{
              jingxitype = 1
              
            }
            that.setData({showjingxi:!0,jingxitype,getsurprise:!0})
          }else{
            that.cleantoast()
            that.setData({['showdaka']:!0})
          }
        })
      }else{
        wx.hideLoading()
        that.cleantoast()
        that.setData({['showdaka']:!0})
      }
     
      //概率 得到奖品
    }
  },

  chose(e){
    let {i} = e.currentTarget.dataset,{choseitem}=this.data,issame=choseitem==i
      that.setData({choseitem:issame?0:i,showshopinfo:!issame})
   
  },

 
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    clearInterval(interval)
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    clearInterval(interval)
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    let {  length,total } = this.data;

    if (length >=total) {
      wx.showToast({
        icon: "none",
        title: '再怎么扯也没有了',
      })
      return;
    }
    that.setData({ start: that.data.start + that.data.pagesize }, () => {
     // that.getlist()
    })
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (opt) {
    console.log(opt,'onShareAppMessage');
    if(opt.from=='button'){
        let {buttonsharecount} = that.data
        if(buttonsharecount<5){
          api.分享({type:"SHARE"},res=>{
            if(res.data.issuccess==1){
              util.nocancelmodal('分享成功')
              api.获取我的积分(res=>{
                if(res.data.issuccess==1){
                  that.setData({totalscore:res.data.score})
                }
              })
              that.setData({buttonsharecount:res.data.count})
            }
          })
        }
    }
    return {
      title: "",
      path: `pages/index/index?share=`+app.logininfo.userid,
    }
  }
})